<?php

class ApiController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('register','question','login','events','event','tickets','shake','vote','iospush', 'timestamp', 'version'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * 注册接口.
	 */
	public function actionRegister()
	{
		header('Content-type: application/json;charset=utf-8');
		if(isset($_POST['User']))
		{
		
			$model=new User;
			$model->attributes=$_POST['User'];
			if($model->save()){
				$ret = array(
					"id" => $model['id'],
					"mobile" => $model['mobile'],
					"username" => $model['username']
				);
				echo json_encode(array('code'=> 0 ,'message'=> "注册成功", 'data'=>$ret));

				$agent = Yii::app()->request->getUserAgent();
				if(stripos($agent, "android") !== false){
					$this->regPush($_POST['User']['userid'], $model['id']);
				}

			}else{
				$user = User::model()->find("mobile=:m and password=:p" , array(':m'=>$model->mobile , ':p'=>$model->password));
				if($user === null){
					$errors = ($model->getErrors());
					$msg = '';
					foreach ($errors as $key => $value) {
						foreach ($value as $sk => $sv) {
							$msg .= $sv;
						}
					}
					echo '{"code": 1004 ,"message": "'.$msg.'"}';
				}else{
					$ret = array("id" => $user['id'],
					"mobile" => $user['mobile'],
					"username" => $user['username']
					);
					echo json_encode(array('code'=> 0 ,'message'=> "登陆成功", 'data'=>$ret));
				}
			}
			Yii::app()->end();
		}

		echo '{"code": 1001 ,"message": "缺少参数或者参数不正确"}';
	}


	private function regPush($udid, $userid){
		$model=new Iospush;
		
		$model->token=$udid;
		$model->userid=$userid;
		$model->os = 'android';

		$model->save();
			 
	}

	/**
	 * 用户登陆.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionLogin()
	{
		header('Content-type: application/json;charset=utf-8');
		// if(isset($_POST['User']))
		// {		  
		// // Apples::model()->find("appleid=:ap" , array(':ap'=>$id));
		// 	// var_dump( );
		// 	// echo $_POST['User']->password;
		// 	// return;
		// 	$user = User::model()->find("mobile=:m and password=:p" , array(':m'=>$_POST['User']['mobile'] , ':p'=>$_POST['User']['password'] ));
		// 	//var_dump($user);
		// 	if ($user === null) {
		// 		echo '{"message": "用户名或密码错误"}';
		// 	}else{
			// $agent = Yii::app()->request->getUserAgent();
			// echo Yii::app()->basePath;

			// $ret = ios_push_message('f3125b3a7e2389d573e27ddcc6a54bee6992a680af0f4f2b25a5bc11ce8bffb9',1,1);
			// echo '推送成功='.$ret;
			// if(stripos($agent, "echo") !== false){
			// 	echo "Chrome";
			// }
			
			//var_dump( Globals::getUser(331) );
			echo '{"message": "Login Succeed"}';
		// 	}
		// 	Yii::app()->end();
		// }

		// echo '{"message": "Login Failure"}';
	}

	/**
	 * 活动列表
	 */
	public function actionEvents()
	{
		header('Content-type: application/json;charset=utf-8');
		$event = Event::model()->findAll(" 1=1 order by id desc");

		$ret = array();
		foreach($event as $v)
		{
			$ret[] = array("id" => $v['id'],
				"title" => $v['title'],
				"description" => $v['description'],
				"share" => $v['share'],
				"thumbnail" => str_replace(dirname(Yii::app()->BasePath) , Yii::app()->request->hostInfo.dirname(Yii::app()->homeUrl) , $v['thumbnail']),
				"thumbnailheight" => $v['thumbnailheight'],
				"background" => str_replace(dirname(Yii::app()->BasePath) , Yii::app()->request->hostInfo.dirname(Yii::app()->homeUrl) , $v['background']),
				"hit" => $v['hit'],
				"award" => $this->award($v['award']),
				"starttime" => strtotime($v['starttime'])<0?0:strtotime($v['starttime']),
				"endtime" => strtotime($v['endtime'])<0?0:strtotime($v['endtime'])
				);
		}

		 
		
		echo json_encode(array('code'=> 0 ,'message'=> "", 'data'=>$ret));
	}

	/**
	 * 活动列表
	 */
	public function actionEvent($eventid)
	{
		header('Content-type: application/json;charset=utf-8');
		$v = Event::model()->findByPk($eventid);
		// var_dump($event);
		if($v === null){
			echo json_encode(array('code'=> 1003 ,'message'=> "没有找到这个活动。"));
		}else{
			$ret = array("id" => $v['id'],
				"title" => $v['title'],
				"description" => $v['description'],
				"share" => $v['share'],
				"thumbnail" => str_replace(dirname(Yii::app()->BasePath) , Yii::app()->request->hostInfo.dirname(Yii::app()->homeUrl) , $v['thumbnail']),
				"thumbnailheight" => $v['thumbnailheight'],
				"background" => str_replace(dirname(Yii::app()->BasePath) , Yii::app()->request->hostInfo.dirname(Yii::app()->homeUrl) , $v['background']),
				"hit" => $v['hit'],
				"award" => $this->award($v['award']),
				"starttime" => strtotime($v['starttime'])<0?0:strtotime($v['starttime']),
				"endtime" => strtotime($v['endtime'])<0?0:strtotime($v['endtime'])
				);
			echo json_encode(array('code'=> 0 ,'message'=> "", 'data'=>$ret));
		}

	}

	private function award($str){
		$array = explode("\r\n", $str);
		// $index = 0;
		// $ret = array();
		// 	foreach($array as $v)
		// 	{
		// 		$ret[$index] = $v;
		// 		$index++;
		// 	}
		
		return $array;
	}
	/**
	 * 当前用户的奖券列表
	 */
	public function actionTickets($userid,$eventid)
	{	
		header('Content-type: application/json;charset=utf-8');
		$tickets = Ticket::model()->findAll(" userid=".$userid." and eventid=".$eventid." order by winning desc,id desc");

		$ret = array();
		foreach($tickets as $v)
		{
			$ret[] = array("id" => $v['id'],
				"userid" => $v['userid'],
				"eventid" => $v['eventid'],
				"code" => $v['code'],
				"winning" => $v['winning'],
				"stat" => $v['stat'],
				// "createtime" => $v['createtime']
				);
		}
		echo json_encode(array('code'=> 0 ,'message'=> "", 'data'=>$ret));
	}

	/**
	 * 上传一个奖券
	 */
	public function actionShake()
	{
		header('Content-type: application/json;charset=utf-8');
		if(!isset($_POST['code'])){
			// echo "ddd";
			echo '{"code": 1006}';
			return;
		}
		if(isset($_POST['Ticket']))
		{
			$count = Ticket::model()->count("userid=:u and eventid=:e and code=:c", 
				array(
					':u'=>$_POST['Ticket']['userid'] ,
					':e'=>$_POST['Ticket']['eventid'] ,
					':c'=>$_POST['Ticket']['code'] 
					));
			if ($count > 0) {
				echo '{"code": 0 ,"message": "奖号已经存在."}';
				Yii::app()->end();
			}

			$count = Ticket::model()->count("userid=:u and eventid=:e", 
				array(
					':u'=>$_POST['Ticket']['userid'] ,
					':e'=>$_POST['Ticket']['eventid']
					));
			if ($count > 500) {
				echo '{"code": 1007 ,"message": "您已经摇出所有的奖券了，请等待开奖吧。"}';
				Yii::app()->end();
			}

			$model=new Ticket;
			$model->attributes=$_POST['Ticket'];
			// echo $model->md5().'|'.$_POST["code"];
		 
			// if(0 !== strcmp($_POST["code"] , $model->md5()) ){
			// 	echo '{"code": 1006}';
			// 	return;
			// }
			if($model->save()){
				$ret = array("id" => $model->id,
					"userid" =>  $model->userid,
					"eventid" =>  $model->eventid,
					"code" =>  $model->code
				);
		
				echo json_encode(array('code'=> 0 ,'message'=> "摇奖成功", 'data'=>$ret));
				// echo '{"code": 0 ,"message": "摇奖成功"}';
			}else{
				$errors = ($model->getErrors());
				$msg = '';
				foreach ($errors as $key => $value) {
					//$msg .= $key;
					foreach ($value as $sk => $sv) {
						$msg .= $sv;
					}
				}
				echo '{"code": 1004 ,"message": "'.$msg.'"}';
			}
			Yii::app()->end();
		}

		echo '{"code": 1001 ,"message": "缺少参数或者参数不正确"}';

	}

	/**
	 * 上传问卷调查的结果
	 * @return [type] [description]
	 */
	public function actionVote(){
		header('Content-type: application/json;charset=utf-8');

		if(isset($_POST['Vote']))
		{
			$model=new Vote;
			$model->attributes=$_POST['Vote'];
			if($model->save()){
				echo '{"code": 0 ,"message": "调查问卷提交成功"}';
			}else{
				echo '{"code": 1004 ,"message": "保存失败"}';
			}
		}else{
			echo '{"code": 1001 ,"message": "缺少参数或者参数不正确"}';
		}
	}
	/**
	 * 上传ios token
	 * @return [type] [description]
	 */
	public function actionIospush(){
		header('Content-type: application/json;charset=utf-8');
		if(isset($_POST['Iospush']))
		{	
			 
			if(isset($_POST['Iospush']['token'])){
				$model = Iospush::model()->find("token=:token", array(':token'=>$_POST['Iospush']['token']));
			}
			if($model === null){
				$model=new Iospush;
			}

			$model->attributes=$_POST['Iospush'];
			$model->os = 'ios';

			if($model->save()){
				echo '{"code": 0 ,"message": "注册Token成功"}';
			}else{
				echo '{"code": 1004 ,"message": "保存失败"}';
			}
		}else{
			echo '{"code": 1001 ,"message": "缺少参数或者参数不正确"}';
		}

	}	

	
	/**
	 * 获得应用的版本信息
	 * @return [type] [description]
	 */
	public function actionQuestion($userid, $eventid){
		// header('Content-type: application/json;charset=utf-8');
	
		$models = Question::model()->findAll("eventid=:e", array(':e'=>$eventid));
		$votes = Vote::model()->findAll("eventid=:e and userid=:u", 
			array(':e'=>$eventid, 
				':u'=>$userid));

		$ret = array();
		foreach($models as $v)
		{
			// 检查是否已经回答过了。
			$pass = true;
			foreach ($votes as $vote) {
				if ($v['id'] === $vote['question']) {
					$pass = false;
				}
			}
			if ($pass) {
				# code...
				$q = explode("\r\n", $v['question']);
				$qarr = array();
				$index = 0;
				foreach($q as $qq)
				{
					$qarr[] = array('askid' => $index,
						'ask' => $qq);
					$index++;
				}
				$ret[] = array("questionid" => $v['id'],
					"question" => $v['ask'],
					"eventid" => $v['eventid'],
					"answers" => $qarr
					);
			}
			// var_dump($q);
			// echo $q;
		}

		if(count($models) > 0){

			echo json_encode(array('code'=> 0 ,'message'=> "", 'data'=>$ret));
		}else{
			echo json_encode(array('code'=> 0 ,'message'=> "没有找到问卷调查。", 'data'=>$ret));
		}
			// echo '{"code": 0 ,"message": "" ,"data" : {"appid" : "700579915"}}';
		 
	}
	/**
	* 获取服务器时间戳
	*/
	public function actionTimestamp(){
		header('Content-type: application/json;charset=utf-8');
		
		echo '{"code": 0 ,"message": "" ,"data" : '.time().'}';
		
	}
	/**
	 * 获得应用的版本信息
	 * @return [type] [description]
	 */
	public function actionVersion(){
		header('Content-type: application/json;charset=utf-8');
		$agent = Yii::app()->request->getUserAgent();

		if(stripos($agent, "android") !== false){
			$ret = array("version" => 2,
				"changelog" => "",
				"downloadurl" => "http://app.xayoudao.com/yaoba/yaoba.apk"
				);
			echo json_encode(array('code'=> 0 ,'message'=> "", 'data'=>$ret));

		}else if(stripos($agent, "ios") !== false){
			echo '{"code": 0 ,"message": "" ,"data" : {"appid" : "700579915"}}';
		}
	}

}
